﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyMvc.BLL;
using MyMvc.IBLL;
using MyMvc.Model;
using MyMvc.Model.Models;

namespace BlueHome.Admin.Controllers
{
    public class LiteratureController : Controller
    {
        //
        // GET: /Literature/

        public ActionResult Index()
        {
            return View();
        }
        IArticleService _articleService = new ArticleService();
        IFileService _fileService = new FileService();
        IAboutArticleService _aboutService = new AboutArticleService();
        IAddFileService _addService = new AddFileService();

        //得到所有文档信息
        public ActionResult GetAllLiterature()
        {
           
            
            //分页的数据
            //
            int pageIndex = Request["page"] == null ? 1 : int.Parse(Request["page"]);
            int pageSize = Request["rows"] == null ? 10 : int.Parse(Request["rows"]);

            //封装一个业务逻辑层，来处理分页过滤的事件
            GetModelQuery literatureInfoQuery = new GetModelQuery();
            literatureInfoQuery.pageIndex = pageIndex;
            literatureInfoQuery.pageSize = pageSize;
            literatureInfoQuery.total = 0;

            //放置依赖刷新
            var data = from u in _articleService.LoadSearchData(literatureInfoQuery)
                       select new { u.ID, u.Title, u.Author };

            //var data = _userInfoService.LoadPagerEntities(pageSize, pageIndex, out total, u => true, true, u => u.ID);

            var result = new { total = literatureInfoQuery.total, rows = data };

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 实现添加信息
        /// </summary>
        /// <param name="stu"></param>
        /// <returns></returns>
        public ActionResult AddArticle(Article art)
        {
            //实现对StudentsInfo表的添加信息
            _articleService.AddEntities(art);
            return Content("OK");
        }


     /// <summary>
     /// 删除文档
     /// </summary>
     /// <param name="deleteID"></param>
     /// <param name="title"></param>
     /// <returns></returns>
        public ActionResult DeleteArticleInfo(string deleteID, string Title)
        {

            if (string.IsNullOrEmpty(deleteID))
            {
                return Content("请选择您要删除的数据");
            }
            //截取传递过来的字符串的数字信息
            var idsStr = deleteID.Split(',');

            List<int> deleteIDList = new List<int>();

            foreach (var ID in idsStr)
            {
                deleteIDList.Add(Convert.ToInt32(ID));
            }
            ////删除附件相关表的ID
            //List<int> deleteList = new List<int>();
            //foreach(var id in idsStr)
            //{
            //    deleteList.Add(Convert.ToInt32(id));
            //}
            if (_articleService.DeleteArticle(deleteIDList) > 0)
            {
                return Content("OK");
            }
            return Content("删除失败，请您检查");

        }

        /// <summary>
        /// 添加附件,get提交数据
        /// </summary>
        /// <returns></returns>
        public ActionResult FileAdd(int ID)
        {

            //查询出当前的文档信息
            var currentArticle = _articleService.LoadEntities(c => c.ID == ID).FirstOrDefault();

            //做成一个强类型，传递给前台接收
            ViewData.Model = currentArticle;
            return View();
        }

        MyMvc.Model.Models.File file = new MyMvc.Model.Models.File();
        AddFile addfile = new AddFile();
        Article article = new Article();
        [HttpPost]
        public ActionResult Upload(int? chunk,int chunks, string name,int infoid)
        {
            
            file.FileName = name;
            file.Address = "~/FileUpload";

            //验证一个文件是否完成上传
            int i = chunks - 1;
            if ((int)chunk == i)
            {
                _fileService.AddEntities(file);
                addfile.ArticleID = infoid;
                addfile.FileID = file.ID;
                _addService.AddEntities(addfile);

            }
            var fileUpload = Request.Files[0];
            var uploadPath = Server.MapPath("~/FileUpload");
            chunk = chunk ?? 0;

            //write chunk to disk.  
            string uploadedFilePath = Path.Combine(uploadPath, name);
            using (var fs = new FileStream(uploadedFilePath, chunk == 0 ? FileMode.Create : FileMode.Append))
            {
                var buffer = new byte[fileUpload.InputStream.Length];
                fileUpload.InputStream.Read(buffer, 0, buffer.Length);
                fs.Write(buffer, 0, buffer.Length);
            }

            return Content("Success", "text/plain");
        }


        /// <summary>
        /// 相关文章,get提交数据
        /// </summary>
        /// <returns></returns>
        public ActionResult AboutArticle(int ID)
        {
            //查询出当前的文章信息
            var currentArticle = _articleService.LoadEntities(c => c.ID == ID).FirstOrDefault();

            //做成一个强类型，传递给前台接收
            ViewData.Model = currentArticle;

            var allArticles = _articleService.LoadEntities(c=>c.Category==currentArticle.Category).ToList();
            //使用ViewBag传递给前台
            ViewBag.AllArticles = allArticles;

            ViewBag.ExtistArticleIds = (from r in currentArticle.AboutArticles  
                                     select r.AboutID).ToList();

            return View();
        }

        /// <summary>
        /// 处理添加相关文章，Post请求
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AboutArticle()
        {
            //拿到当前设置文章的ID
            int artId = Request["hidUserId"] == null ? 0 : Convert.ToInt32(Request["hidUserId"]);
            //查询出当前文章
            var currentSetUser = _articleService.LoadEntities(c => c.ID == artId).FirstOrDefault();
            if (currentSetUser != null)
            {
                var allKeys = from key in Request.Form.AllKeys
                              where key.StartsWith("ckb_")
                              select key;                
                //定义一个list集合存放传递过来的Key
                List<int> artIds = new List<int>();
                List<string> namelist = new List<string>();
                if (artId > 0)
                {
                    //循环遍历出所有的前台表单传递过来的数据的信息
                    foreach (var key in allKeys)
                    {
                        artIds.Add(Convert.ToInt32(key.Replace("ckb_", "")));

                    }

                    for (int i = 0; i < artIds.Count; i++)
                    {
                        string name1 = _articleService.LoadEntities(c => c.ID == artIds[i]).FirstOrDefault().Title;
                        namelist.Add(name1);
                    }

                }
                //var allName = from key in Request.Form.AllKeys
                //              where key.StartsWith("name_")
                //              select key;
                //List<string> list1 = new List<string>();
                //if (artId > 0)
                //{
                //    //循环遍历出所有的前台表单传递过来的数据的信息
                //    foreach (var key in allKeys)
                //    {
                //        artIds.Add(Convert.ToInt32(key.Replace("ckb_", "")));
           
                //    }
                    
                //    for (int i = 0; i < artIds.Count; i++)
                //    {
                //        string name1 = _articleService.LoadEntities(c => c.ID == artIds[i]).FirstOrDefault().Title;
                //        list1.Add(name1);
                //    }

                //    foreach(var name in allName)
                //    {
                //        namelist.Add(name.Replace("name_",""));
                //    }
                //}
                _articleService.AboutArticle(artId, artIds, namelist);
            }
            return Content("OK");
        }
    }
}
